package com.edu.admin.service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.edu.admin.common.BaseService;
import com.edu.admin.entity.SysSchool;
import com.edu.admin.entity.SysSchoolRole;
import com.edu.admin.entity.SysUser;
import com.edu.admin.entity.SysUserSubject;
import com.edu.admin.enums.ExceptionEnum;
import com.edu.admin.enums.GenderTypeEnum;
import com.edu.admin.enums.UseTypeEnum;
import com.edu.admin.enums.UserTypeEnum;
import com.edu.admin.exception.SysException;
import com.edu.admin.mapper.ClassesTeacherMapper;
import com.edu.admin.mapper.SchoolMapper;
import com.edu.admin.mapper.UserMapper;
import com.edu.admin.utils.ExcelUtils;
import com.edu.admin.utils.NumberUtils;
import com.edu.admin.utils.UploadUtil;
import com.edu.admin.vo.ClassesVo;
import com.edu.admin.vo.SchoolPhaseVo;
import com.edu.admin.vo.SchoolRoleVo;
import com.edu.admin.vo.SchoolVo;
import com.edu.admin.vo.UserSubjectVo;
import com.edu.admin.vo.UserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 用户表服务
 * 
 * @author Wangjiong
 * 
 */
@Transactional
@Service
public class UserService extends BaseService<UserMapper, SysUser> {
	
	@Autowired
	SchoolMapper schoolMapper;
	@Autowired
	ClassesTeacherMapper classesTeacherMapper;
	@Autowired
	UserSubjectService userSubjectService;
	@Autowired
	ClassesService classesService;
	@Autowired
	SchoolService schoolService;
	@Autowired
	SchoolRoleService schoolRoleService;
	@Autowired
	SchoolPhaseService schoolPhaseService;
	@Autowired
	SubjectService subjectService;
	@Autowired
	BCryptPasswordEncoder passwordEncoder;
	
	
	/**
	 * 获取用户信息
	 * 
	 * @param username
	 * 
	 * @return SysUser
	 */
	public SysUser findUserByUsername(String username) {
		return this.mapper.findUserByUsername(username);
	}
	
	/**
	 * 获取用户信息
	 * 
	 * @param userId
	 * 
	 * @return UserVo
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public UserVo getUserById(Long userId) throws IllegalAccessException, InvocationTargetException{
		
		UserVo userVo = this.mapper.getUserById(userId);
		
		return userVo;
	}
	
	/**
	 * 条件搜索可用教师列表
	 * 
	 * @param schoolId
	 * @param userName
	 * @param account
	 * 
	 * @return List<UserVo>
	 */
	public List<UserVo> getTeacherListBySchoolId(Long schoolId, String userName,String account,Integer isGraduated) {
			
		List<UserVo> userList = this.mapper.findUserListBySchool(UserTypeEnum.TEACHER.getCode(),
																	UseTypeEnum.ISUSE.getCode(),
																	schoolId,null,userName,account,
																	isGraduated);
		for (UserVo user: userList)
		{
            List<UserSubjectVo> userSubjectList = userSubjectService.getUserSubjectList(user.getUserId());
            List<Long> subjectList = new ArrayList<Long>();

            if (userSubjectList!=null && userSubjectList.size()>0)
            {
	            for (UserSubjectVo userSubjectVo: userSubjectList)
	            {
	            	subjectList.add(userSubjectVo.getSubjectId());
	            }
	            
            }
            
            int size = subjectList.size();  
            Long[] subjects = (Long[])subjectList.toArray(new Long[size]);  
            
            user.setSubjects(subjects);

        }
	
		return userList;
	}

	/**
	 * 条件搜索可用教师列表 (分页)
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @param schoolId
	 * @param userName
	 * @param account
	 * 
	 * @return PageInfo<UserVo>
	 */
	public PageInfo<UserVo> getTeacherListPageBySchoolId(Integer pageNum, Integer pageSize, 
											Long schoolId, String userName,String account,
											Integer isGraduated) {
		if (pageNum == null) {
			pageNum = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		PageHelper.startPage(pageNum, pageSize);
		
		List<UserVo> userList = this.mapper.findUserListBySchool(UserTypeEnum.TEACHER.getCode(),
																	UseTypeEnum.ISUSE.getCode(),
																	schoolId,null,userName,account,
																	isGraduated);
		
		for (UserVo user: userList)
		{
            List<UserSubjectVo> userSubjectList = userSubjectService.getUserSubjectList(user.getUserId());
            List<Long> subjectList = new ArrayList<Long>();

            if (userSubjectList!=null && userSubjectList.size()>0)
            {
	            for (UserSubjectVo userSubjectVo: userSubjectList)
	            {
	            	subjectList.add(userSubjectVo.getSubjectId());
	            }
	            
            }
            
            int size = subjectList.size();  
            Long[] subjects = (Long[])subjectList.toArray(new Long[size]);  
            
            user.setSubjects(subjects);

        }
															
		PageInfo<UserVo> pageInfo = new PageInfo<UserVo>(userList);

		return pageInfo;
	}
	
	/**
	 * 条件搜索所有教师列表 (分页)
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @param schoolId
	 * @param userName
	 * @param account
	 * 
	 * @return PageInfo<UserVo>
	 */
	public PageInfo<UserVo> getAllTeacherListPageBySchoolId(Integer pageNum, Integer pageSize, 
											Long schoolId, String userName,String account,
											Integer isGraduated) {
		if (pageNum == null) {
			pageNum = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		PageHelper.startPage(pageNum, pageSize);
		
		List<UserVo> userList = this.mapper.findUserListBySchool(UserTypeEnum.TEACHER.getCode(),
																	null,schoolId,null,userName,
																	account,isGraduated);
		for (UserVo user: userList)
		{
            List<UserSubjectVo> userSubjectList = userSubjectService.getUserSubjectList(user.getUserId());
            List<Long> subjectList = new ArrayList<Long>();

            if (userSubjectList!=null && userSubjectList.size()>0)
            {
	            for (UserSubjectVo userSubjectVo: userSubjectList)
	            {
	            	subjectList.add(userSubjectVo.getSubjectId());
	            }
	            
            }
            
            int size = subjectList.size();  
            Long[] subjects = (Long[])subjectList.toArray(new Long[size]);  
            
            user.setSubjects(subjects);

        }
		
		PageInfo<UserVo> pageInfo = new PageInfo<UserVo>(userList);

		return pageInfo;
	}
	
	/**
	 * 条件搜索可用教师列表 (分页)
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @param schoolName
	 * @param userName
	 * @param account
	 * 
	 * @return
	 */
	public PageInfo<UserVo> getTeacherListBySchoolName(Integer pageNum, Integer pageSize, 
											String schoolName, String userName,String account,
											Integer isGraduated) {
		if (pageNum == null) {
			pageNum = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		PageHelper.startPage(pageNum, pageSize);
		
		List<UserVo> userList =  this.mapper.findUserListBySchool(UserTypeEnum.TEACHER.getCode(),
																	UseTypeEnum.ISUSE.getCode(),
																	null,schoolName,userName,account,
																	isGraduated);
		
		for (UserVo user: userList)
		{
            List<UserSubjectVo> userSubjectList = userSubjectService.getUserSubjectList(user.getUserId());
            List<Long> subjectList = new ArrayList<Long>();

            if (userSubjectList!=null && userSubjectList.size()>0)
            {
	            for (UserSubjectVo userSubjectVo: userSubjectList)
	            {
	            	subjectList.add(userSubjectVo.getSubjectId());
	            }
	            
            }
            
            int size = subjectList.size();  
            Long[] subjects = (Long[])subjectList.toArray(new Long[size]);  
            
            user.setSubjects(subjects);

        }
		
		PageInfo<UserVo> pageInfo = new PageInfo<UserVo>(userList);

		return pageInfo;
	}
	
	/**
	 * 条件搜索所有教师列表 (分页)
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @param schoolName
	 * @param userName
	 * @param account
	 * 
	 * @return
	 */
	public PageInfo<UserVo> getAllTeacherListBySchoolName(Integer pageNum, Integer pageSize, 
											String schoolName, String userName,String account,
											Integer isGraduated) {
		if (pageNum == null) {
			pageNum = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		PageHelper.startPage(pageNum, pageSize);
		
		List<UserVo> userList =  this.mapper.findUserListBySchool(UserTypeEnum.TEACHER.getCode(),
																	null,null,schoolName,userName,account,
																	isGraduated);
		
		for (UserVo user: userList)
		{
            List<UserSubjectVo> userSubjectList = userSubjectService.getUserSubjectList(user.getUserId());
            List<Long> subjectList = new ArrayList<Long>();

            if (userSubjectList!=null && userSubjectList.size()>0)
            {
	            for (UserSubjectVo userSubjectVo: userSubjectList)
	            {
	            	subjectList.add(userSubjectVo.getSubjectId());
	            }
	            
            }
            
            int size = subjectList.size();  
            Long[] subjects = (Long[])subjectList.toArray(new Long[size]);  
            
            user.setSubjects(subjects);

        }
		
		PageInfo<UserVo> pageInfo = new PageInfo<UserVo>(userList);

		return pageInfo;
	}
	
	/**
	 * 按学段，学科，姓名查询教师列表
	 * 
	 * @param schoolId
	 * @param phaseId
	 * @param subjectId
	 * @param userName
	 * 
	 * @return List<UserVo>
	 * 
	 */
	public List<UserVo> findTeacherListBySubjectId(Long schoolId, Long phaseId, Long subjectId, String userName) {
			
		List<UserVo> userList = this.mapper.findTeacherListBySubjectId(UseTypeEnum.ISUSE.getCode(),
																	schoolId,phaseId,subjectId,userName);
		for (UserVo user: userList)
		{
            List<UserSubjectVo> userSubjectList = userSubjectService.getUserSubjectList(user.getUserId());
            List<Long> subjectList = new ArrayList<Long>();
            String subjectName="";

            if (userSubjectList!=null && userSubjectList.size()>0)
            {
	            for (UserSubjectVo userSubjectVo: userSubjectList)
	            {
	            	subjectList.add(userSubjectVo.getSubjectId());
	            	if (subjectName.isEmpty())
	            	{
	            		subjectName = userSubjectVo.getSubjectName();
	            	}
	            	else
	            	{
	            		subjectName = subjectName + ","+userSubjectVo.getSubjectName();
	            	}
	            }
	            
            }
            
            int size = subjectList.size();  
            Long[] subjects = (Long[])subjectList.toArray(new Long[size]);  
            
            user.setSubjects(subjects);
            user.setSubjectName(subjectName);

        }
	
		return userList;
	}
	
	/**
	 * 条件搜索可用学生列表 (分页)
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @param schoolName
	 * @param userName
	 * @param account
	 * 
	 * @return
	 */
	public PageInfo<UserVo> getStudentListBySchoolName(Integer pageNum, Integer pageSize, 
											String schoolName, String userName,String account,Integer isGraduated) {
		if (pageNum == null) {
			pageNum = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		PageHelper.startPage(pageNum, pageSize);
		
		List<UserVo> userList =  this.mapper.findUserListBySchool(UserTypeEnum.STUDENT.getCode(),
																	null,null,schoolName,userName,account,isGraduated);
		
		PageInfo<UserVo> pageInfo = new PageInfo<UserVo>(userList);

		return pageInfo;
	}
	
	
	/**
	 * 条件搜索可用学生列表 (分页)
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @param schoolId
	 * @param phaseId
	 * @param gradeId
	 * @param classesId
	 * @param userName
	 * @param account
	 * 
	 * @return
	 */
	public PageInfo<UserVo> getStudentListByClassesId(Integer pageNum, Integer pageSize, 
										Long schoolId, Long phaseId, Long gradeId, 
										Long classesId,String userName,String account,Integer isGraduated) {
		if (pageNum == null) {
			pageNum = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		PageHelper.startPage(pageNum, pageSize);
		
		List<UserVo> userList =  this.mapper.findUserListByClassesId(UserTypeEnum.STUDENT.getCode(),
														null,schoolId,phaseId,gradeId,classesId,userName,account,isGraduated);
		
		PageInfo<UserVo> pageInfo = new PageInfo<UserVo>(userList);

		return pageInfo;
	}
	
	
	/**
	 * 搜索学生数量
	 * 
	 * @param schoolId
	 * @param phaseId
	 * @param gradeId
	 * @param classesId

	 * 
	 * @return
	 */
	public Integer getStudentCount(Long schoolId, Long phaseId, Long classesId)
	{

		Integer userCount =  this.mapper.getUserCount(UserTypeEnum.STUDENT.getCode(),
													schoolId,phaseId,classesId);

		return userCount;
	}
	
	/**
     * 教师/学生重复性检查
     * 
     * @param newUser
     * @param type
     * 
     * @return List<UserVo>
     * @throws Exception
     */
    public List<UserVo> checkUser(SysUser newUser, int type) throws Exception {
    	
    	return this.mapper.findUserByAccount(type, newUser.getUserId(), newUser.getAccount().trim());
  
    }
	
	
	/**
	 * 用户保存
	 * 
	 * @param newUser
	 * @param type
	 * 
	 * @return Map<String, Object>
	 */
	private Map<String, Object> saveUser(SysUser newUser, int type) {
		Map<String, Object> result = new HashMap<>();
		
		Long userId = newUser.getUserId();

		if (userId == null) {
			if (type>0)
			{
				newUser.setType(type);
			}

			newUser.setUseType(UseTypeEnum.ISUSE.getCode());
			
			insert(newUser);
			
			userId = newUser.getUserId();


		} else {
			
			updateByPrimaryKeySelective(newUser);

		}
		
		if (type!=UserTypeEnum.STUDENT.getCode())
		{
			userSubjectService.deleteUserSubjectByUserId(userId);
			
			Long[] subjects = newUser.getSubjects();
			
			if (subjects!=null && subjects.length >0)
			{
				for (int i=0;i<subjects.length;i++)
				{
					SysUserSubject userSubject = new SysUserSubject();
					userSubject.setUserId(userId);
					userSubject.setSubjectId(new Long(subjects[i]));
					userSubjectService.insert(userSubject);
				}
			}
		}
		
		result.put("userId", userId);

		return result;

	}
	
	/**
	 * 教师保存
	 * 
	 * @param newUser
	 * 
	 * @return Map<String, Object>
	 * @throws Exception 
	 */
	public Map<String, Object> saveTeacher(SysUser newUser) throws Exception {
		newUser.setAccount(newUser.getPhone());
		newUser.setPassword(passwordEncoder.encode("123456"));
		
		List<UserVo> userList = checkUser(newUser,UserTypeEnum.TEACHER.getCode());
		
		if (userList!=null && userList.size()>0)
		{
			throw new SysException(ExceptionEnum.TEACHERREPEAT);
		}
		
		return saveUser(newUser,UserTypeEnum.TEACHER.getCode());

	}
	
	
	/**
	 * 学生保存
	 * 
	 * @param newUser
	 * 
	 * @return Map<String, Object>
	 * @throws Exception 
	 */
	public Map<String, Object> saveStudent(SysUser newUser) throws Exception {
		newUser.setAccount(newUser.getStudentNo());
		newUser.setPassword(passwordEncoder.encode("123456"));
		
		List<UserVo> userList = checkUser(newUser,UserTypeEnum.STUDENT.getCode());
		
		if (userList!=null && userList.size()>0)
		{
			throw new SysException(ExceptionEnum.STUDENTREPEAT);
		}
		
		return saveUser(newUser,UserTypeEnum.STUDENT.getCode());

	}
	
	/**
	 * 删除学生/教师
	 * 
	 * @param userId
	 * 
	 * @return int
	 */
	public int deleteUser(Long userId) {
		
		if (userId != null) {
			return this.deleteByPrimaryKey(userId);

		}
		
		return 0;	

	}
	
	
	/**
	 * 用户密码重置保存
	 * 
	 * @param userId
	 * 
	 * @return int
	 */
	public int restUserPassword(Long userId) {
		
		if (userId != null) {
			SysUser newUser = new SysUser();
			newUser.setUserId(userId);
			newUser.setPassword(passwordEncoder.encode("123456"));
			return updateByPrimaryKeySelective(newUser);

		}
		
		return 0;

	}
	
	/**
	 * 批量启用或停用学生/教师
	 * 
	 * @param idList
	 * @param isUse
	 * 
	 * @return
	 */
	public void batchUse(Long[] idList,int isUse) {
		
		if(idList == null){
            return;
        }
		
        for (int i = 0;i < idList.length;i++){
            SysUser newUser = new SysUser();
            newUser.setUserId(idList[i]);
            newUser.setUseType(isUse);
            saveUser(newUser,0);
        }

	}
	
	/**
	 * 启用停用教师
	 * 
	 * @param userId
	 * @param useType
	 * 
	 * @return
	 */
	public int useUser(Long userId,Integer useType) {
		
		if (userId != null) {
			SysUser user = new SysUser();
			user.setUserId(userId);
			user.setUseType(useType);
			return updateByPrimaryKeySelective(user);

		}
		
		return 0;	

	}
	
	
	/**
	 * 教师转校
	 * 
	 * @param idList
	 * @param schoolId
	 * 
	 * @return
	 */
	public void moveTeachers(Long[] idList,Long schoolId) {
		
		if(idList == null){
            return;
        }
		
		SysSchool school = schoolMapper.selectByPrimaryKey(schoolId);
        for (int i = 0;i < idList.length;i++) {
            SysUser newUser = new SysUser();
            newUser.setUserId(idList[i]);
            newUser.setSchoolId(schoolId);
            newUser.setProvinceCode(school.getProvinceCode());
            newUser.setCityCode(school.getCityCode());
            newUser.setDistrictCode(school.getDistrictCode());
            int isOk = updateByPrimaryKeySelective(newUser);
            //删除教师与原来班级的关系
            if (isOk>0)
            {
                classesTeacherMapper.deleteClassesTeacherByTeacherId(idList[i]);
            }
        }

	}
	
	/**
	 * 教师转校
	 * 
	 * @param ids
	 * @param schoolId
	 * @param phaselId
	 * @param classesId
	 * 
	 * @return
	 */
	public void moveStudents(Long[] ids,Long schoolId,Long phaselId, Long classesId) {
		
		if(ids == null){
            return;
        }
		
		SysSchool school = schoolMapper.selectByPrimaryKey(schoolId);
        for (int i = 0;i < ids.length;i++) {
            SysUser newUser = new SysUser();
            newUser.setUserId(ids[i]);
            newUser.setSchoolId(schoolId);
            newUser.setClassesId(classesId);
            newUser.setPhaseId(phaselId);
            newUser.setProvinceCode(school.getProvinceCode());
            newUser.setCityCode(school.getCityCode());
            newUser.setDistrictCode(school.getDistrictCode());
            updateByPrimaryKeySelective(newUser);

        }

	}
	
	/**
	 * 移出校
	 * 
	 * @param idList
	 *  
	 * @return
	 */
	public void outSchool(Long[] idList) {
        if(idList == null){
            return;
        }
        for (int i = 0;i < idList.length;i++){
            SysUser newUser = selectByPrimaryKey(idList[i]);
            newUser.setSchoolId(null);
            newUser.setClassesId(null);
            updateByPrimaryKey(newUser);
        }

    }
	
	/**
	 * 移出班
	 * 
	 * @param idList
	 * 
	 * @return
	 */
	public void outClasses(Long[] idList) {
        if(idList == null){
            return;
        }
        for (int i = 0;i < idList.length;i++){
            SysUser newUser = selectByPrimaryKey(idList[i]);
            newUser.setClassesId(null);
            updateByPrimaryKey(newUser);
        }

    }
	
	/**
	 * 导入学生
	 * 
	 * @param file
	 * @param schoolId
	 * @param request
	 * 
	 * @return Map<String, Object>
	 * 
	 * @throws Exception
	 */
	public Map<String, Object> importStudent(MultipartFile file, 
									Long schoolId, 
									HttpServletRequest request) throws Exception {

		int iRow = 0;
		String orderNumField = "序号（必填）";  // 序号列名
		String classesNameField = "班级名称（必填）";// 班级名称列名
		String userNameField = "学生姓名（必填）";// 学生姓名列名
		String studentNoField = "学籍号（必填）";// 学籍号列名
		String genderField = "性别";// 性别列名
		String birthdayField = "出生日期";// 生日列名
		Integer orderNum;  // 序号
		String classesName;// 班级名称列名
		String userName;// 学生姓名
		String studentNo;// 学籍号
		String gender;// 性别
		String birthday;// 生日
		Long classesId;
		Long phaseId;
		
		Map<String, Object> result = new HashMap<>();
		
		List<Map<String, Object>> errorList = new ArrayList<>();

		UploadUtil uploadUtil = new UploadUtil();

		String filePath = uploadUtil.upload(file, schoolId ,request);
		if (filePath == null) {
			throw new SysException(ExceptionEnum.UPLOADERROR);
		}

		String[] attrs = { "orderNum", "classesName", "userName", "studentNo", "gender", "birthday" };
		List<Map<String, Object>> studentList = ExcelUtils.importExcel(filePath, 0, 0, attrs);
		
		SchoolVo school = schoolService.getSchool(schoolId);
		String provinceCode = school.getProvinceCode();
		String cityCode = school.getCityCode();
		String districtCode = school.getDistrictCode();

		for (Map<String, Object> student : studentList) {
			
			Map<String, Object> errorInfo = new HashMap<>();
			
			try {
				if (iRow == 0) {
					
					StringBuilder errorBuilder = new StringBuilder();
					
					orderNumField = MapUtils.getString(student, "orderNum");//序号
					classesNameField = MapUtils.getString(student, "classesName");// 班级名称
					userNameField = MapUtils.getString(student, "userName");// 学生姓名
					studentNoField = MapUtils.getString(student, "studentNo");// 学籍号
					genderField = MapUtils.getString(student, "gender");// 性别
					birthdayField = MapUtils.getString(student, "birthday");// 生日
					
					if (orderNumField.indexOf("序号")<0) {
						errorBuilder.append("第一列必须是序号列").append(",");
					}
					
					if (classesNameField.indexOf("班级名称")<0) {
						errorBuilder.append("第二列必须是班级名称列").append(",");
					}
					
					if (userNameField.indexOf("学生姓名")<0) {
						errorBuilder.append("第三列必须是学生姓名列").append(",");
					}
					
					if (studentNoField.indexOf("学籍号")<0) {
						errorBuilder.append("第四列必须是学籍号列").append(",");
					}
					
					if (genderField.indexOf("性别")<0) {
						errorBuilder.append("第五列必须是性别列").append(",");
					}
					
					if (birthdayField.indexOf("出生日期")<0) {
						errorBuilder.append("第六列必须是出生日期列").append(",");
					}
					
					if (errorBuilder.length()>0)
					{
						errorInfo.put("orderNum", 0);
						errorInfo.put("info", errorBuilder.substring(0, errorBuilder.length()-2));
						errorList.add(errorInfo);
						
						result.put("statusinfo", "error");
						result.put("errordata", errorList);
						
						return result;
					}
					

				} 
				else
				{
					
					orderNum = MapUtils.getInteger(student, orderNumField);//序号
					errorInfo.put("orderNum", orderNum);
					
					if (orderNum==null)
					{
						continue;
					}
									
					classesName = MapUtils.getString(student, classesNameField);// 班级名称
					userName = MapUtils.getString(student, userNameField);// 学生姓名
					studentNo = NumberUtils.FormatFloat(MapUtils.getString(student, studentNoField));// 学籍号
					gender = MapUtils.getString(student, genderField);// 性别
					birthday = MapUtils.getString(student, birthdayField);// 生日
					
					if (classesName==null || classesName.trim().isEmpty()) 
					{
						errorInfo.put("info", "班级名称为空");
						errorList.add(errorInfo);
						continue;
					}
					else
					{
						ClassesVo classes = classesService.getClassesByName(schoolId, classesName.trim());
						
						if (classes==null)
						{
							errorInfo.put("info", "班级不存在");
							errorList.add(errorInfo);
							continue;
						}
						else
						{
							classesId = classes.getClassesId();
							phaseId = classes.getPhaseId();

						}
						
					}
					
					if (userName==null || userName.trim().isEmpty()) 
					{
						errorInfo.put("info", "学生姓名为空");
						errorList.add(errorInfo);
	                    continue;
	                }
					
					if (studentNo==null || studentNo.trim().isEmpty()) 
					{
						errorInfo.put("info", "学籍号为空");
						errorList.add(errorInfo);
						continue;
					}
					
					
	
					SysUser newUser = new SysUser();
					
					newUser.setAccount(studentNo);
					newUser.setStudentNo(studentNo);
					newUser.setUserName(userName);
					newUser.setSchoolId(schoolId);
					newUser.setClassesId(classesId);
					newUser.setPassword(passwordEncoder.encode("123456"));
					newUser.setBirthday(birthday);
					newUser.setPhaseId(phaseId);
					newUser.setProvinceCode(provinceCode);
					newUser.setCityCode(cityCode);
					newUser.setDistrictCode(districtCode);
					
					if (gender!=null)
					{
						if(GenderTypeEnum.MAN.getMsg().equals(gender.trim())){
							newUser.setGender(GenderTypeEnum.MAN.getCode().toString());
		                }else{
		                	newUser.setGender(GenderTypeEnum.WOMAN.getCode().toString());
		                }
					}
					
					List<UserVo> userList = checkUser(newUser,UserTypeEnum.STUDENT.getCode());
					
					if (userList!=null && userList.size()>0)
					{
						errorInfo.put("info", "学籍号重复");
						errorList.add(errorInfo);
						continue;
					}
										
					saveUser(newUser,UserTypeEnum.STUDENT.getCode());
										
				}

			} catch (Exception e) {
				e.printStackTrace();
				errorInfo.put("info", "学生保存失败");
				errorList.add(errorInfo);
			}

			iRow++;
		}

		// 统计学校班级、教师、学生数据
		schoolService.updateSchoolStudentNumBySchoolId(schoolId);

		if (errorList.size() > 0) {
			result.put("statusinfo", "error");
			result.put("errordata", errorList);
		} else {
			result.put("statusinfo", "success");
		}

		return result;
	}
	
	/**
	 * 导入教师
	 * 
	 * @param file
	 * @param schoolId
	 * @param request
	 * 
	 * @return Map<String, Object>
	 * 
	 * @throws Exception
	 */
	public Map<String, Object> importTeacher(MultipartFile file, 
									Long schoolId, 
									HttpServletRequest request) throws Exception {

		int iRow = 0;
		int emptyRow = 0;
		
		String orderNumField = "序号（必填）";  
		String userNameField = "教师姓名（必填）";
		String phoneField = "手机号（必填）";
		String genderField = "性别（必填）";
		String roleNameField = "角色（必填）";
		String phaseNameField = "学段（必填）";
		String teacherNoField = "教师编号";
		String subject1Field = "学科1";
		String subject2Field = "学科2";
		String subject3Field = "学科3";
		String subject4Field = "学科4";
		String subject5Field = "学科5";
		
		Integer orderNum;  // 序号
		String userName; // 教师姓名
		Long phone; // 手机号
		String gender;// 性别
		String roleName;// 角色
		String phaseName; //学段（必填）
		String teacherNo; //教师编号
		String subject1; //学科1
		String subject2; //学科2
		String subject3; //学科3
		String subject4; //学科4
		String subject5; //学科5
		
		Long roleId;
		Long phaseId;

		
		Map<String, Object> result = new HashMap<>();
		
		List<Map<String, Object>> errorList = new ArrayList<>();

		UploadUtil uploadUtil = new UploadUtil();

		String filePath = uploadUtil.upload(file, schoolId ,request);
		if (filePath == null) {
			throw new SysException(ExceptionEnum.UPLOADERROR);
		}

		String[] attrs = { "orderNum", "userName", "phone", "gender", "roleName", "phaseName",
						"teacherNo", "subject1", "subject2", "subject3", "subject4", "subject5"};
		
		List<Map<String, Object>> teacherList = ExcelUtils.importExcel(filePath, 0, 0, attrs);
		
		SchoolVo school = schoolService.getSchool(schoolId);
		String provinceCode = school.getProvinceCode();
		String cityCode = school.getCityCode();
		String districtCode = school.getDistrictCode();
		
		for (Map<String, Object> teacher : teacherList) {
			
			Map<String, Object> errorInfo = new HashMap<>();
			
			try {
				if (iRow == 0) {
					
					StringBuilder errorBuilder = new StringBuilder();
					
					orderNumField = MapUtils.getString(teacher, "orderNum");//序号
					userNameField = MapUtils.getString(teacher, "userName");// 教师姓名
					phoneField = MapUtils.getString(teacher, "phone");// 教师手机号
					genderField = MapUtils.getString(teacher, "gender");// 性别
					roleNameField = MapUtils.getString(teacher, "roleName");// 角色
					phaseNameField = MapUtils.getString(teacher, "phaseName");// 学段
					teacherNoField = MapUtils.getString(teacher, "teacherNo");// 教师编号
					subject1Field = MapUtils.getString(teacher, "subject1");// 学科1
					subject2Field = MapUtils.getString(teacher, "subject2");// 学科2
					subject3Field = MapUtils.getString(teacher, "subject3");// 学科3
					subject4Field = MapUtils.getString(teacher, "subject4");// 学科4
					subject5Field = MapUtils.getString(teacher, "subject5");// 学科5
						
					
					if (orderNumField.indexOf("序号")<0) {
						errorBuilder.append("第一列必须是序号列").append(",");
					}
					
					if (userNameField.indexOf("教师姓名")<0) {
						errorBuilder.append("第二列必须是教师姓名列").append(",");
					}
					
					if (phoneField.indexOf("手机号")<0) {
						errorBuilder.append("第三列必须是手机号列").append(",");
					}
					
					if (genderField.indexOf("性别")<0) {
						errorBuilder.append("第四列必须是性别列").append(",");
					}
					
					if (roleNameField.indexOf("角色")<0) {
						errorBuilder.append("第五列必须是角色列").append(",");
					}
					
					if (phaseNameField.indexOf("学段")<0) {
						errorBuilder.append("第六列必须是学段列").append(",");
					}
					
					if (teacherNoField.indexOf("教师编号")<0) {
						errorBuilder.append("第七列必须是教师编号列").append(",");
					}
					
					if (errorBuilder.length()>0)
					{
						errorInfo.put("orderNum", 0);
						errorInfo.put("info", errorBuilder.substring(0, errorBuilder.length()-2));
						errorList.add(errorInfo);
						
						result.put("statusinfo", "error");
						result.put("errordata", errorList);
						
						return result;
					}
					

				} 
				else
				{   
					// 如果空行太多表示文档已经导完
					if (emptyRow>10)
					{
						break;
					}
					
					orderNum = MapUtils.getInteger(teacher, orderNumField);//序号
					errorInfo.put("orderNum", orderNum);
					
					if (orderNum==null)
					{
						emptyRow++;
						continue;
					}
					
					emptyRow = 0;
					userName = MapUtils.getString(teacher, userNameField);// 教师姓名
					phone = MapUtils.getLong(teacher, phoneField);// 教师手机号
					gender = MapUtils.getString(teacher, genderField);// 性别
					roleName = MapUtils.getString(teacher, roleNameField);// 角色
					phaseName = MapUtils.getString(teacher, phaseNameField);// 学段
					teacherNo = NumberUtils.FormatFloat(MapUtils.getString(teacher, teacherNoField));// 教师编号
					subject1 = MapUtils.getString(teacher, subject1Field);// 学科1
					subject2 = MapUtils.getString(teacher, subject2Field);// 学科2
					subject3 = MapUtils.getString(teacher, subject3Field);// 学科3
					subject4 = MapUtils.getString(teacher, subject4Field);// 学科4
					subject5 = MapUtils.getString(teacher, subject5Field);// 学科5
					
					
					
					if (userName==null || userName.trim().isEmpty()) 
					{
						errorInfo.put("info", "教师姓名为空");
						errorList.add(errorInfo);
	                    continue;
	                }
					
					if (phone==null || phone==0) 
					{
						errorInfo.put("info", "教师手机号为空");
						errorList.add(errorInfo);
	                    continue;
	                }
					
					if (gender==null || gender.trim().isEmpty()) 
					{
						errorInfo.put("info", "性别为空");
						errorList.add(errorInfo);
	                    continue;
	                }
					
					if (roleName==null || roleName.trim().isEmpty()) 
					{
						errorInfo.put("info", "角色为空");
						errorList.add(errorInfo);
						continue;
					}
					else
					{
						SysSchoolRole role = new SysSchoolRole();
						role.setSchoolId(schoolId);
						role.setSchoolRoleName(roleName);
						
						List<SchoolRoleVo> roleVo = schoolRoleService.checkSchoolRole(role);
						
						if (roleVo==null || roleVo.size()==0)
						{
							errorInfo.put("info", "角色不存在");
							errorList.add(errorInfo);
							continue;
						}
						else
						{
							roleId = roleVo.get(0).getSchoolRoleId();
						}
						
					}
					
					if (phaseName==null || phaseName.trim().isEmpty()) 
					{
						errorInfo.put("info", "学段为空");
						errorList.add(errorInfo);
						continue;
					}
					
					List<SchoolPhaseVo> phaseList = schoolPhaseService.getSchoolPhaseBySchoolIdAndPhaseName(schoolId, phaseName);
	                if(phaseList == null || phaseList.size()==0){
	                	errorInfo.put("info","学段不存在");
	                	errorList.add(errorInfo);
	                    continue;
	                }
	                else
	                {
	                	phaseId = phaseList.get(0).getPhaseId();
	                }
					
//					if (teacherNo==null || teacherNo.trim().isEmpty()) 
//					{
//						errorInfo.put("info", "教师编号为空");
//						errorList.add(errorInfo);
//						continue;
//					}
					
						
					SysUser newUser = new SysUser();
					
					newUser.setAccount(phone.toString());
					newUser.setPhone(phone.toString());
					newUser.setUserName(userName);
					newUser.setSchoolId(schoolId);
					newUser.setPassword(passwordEncoder.encode("123456"));
					newUser.setTeacherNo(teacherNo);
					newUser.setRoleId(roleId);
					newUser.setPhaseId(phaseId);
					newUser.setProvinceCode(provinceCode);
					newUser.setCityCode(cityCode);
					newUser.setDistrictCode(districtCode);
					
					if (gender!=null)
					{
						if(GenderTypeEnum.MAN.getMsg().equals(gender.trim())){
							newUser.setGender(GenderTypeEnum.MAN.getCode().toString());
		                }else{
		                	newUser.setGender(GenderTypeEnum.WOMAN.getCode().toString());
		                }
					}
					
					List<UserVo> userList = checkUser(newUser,UserTypeEnum.TEACHER.getCode());
					
					if (userList!=null && userList.size()>0)
					{
						errorInfo.put("info", "教师手机号已存在");
						errorList.add(errorInfo);
						continue;
					}
					
					List<String> subjectNameList = new ArrayList<String>();
					
					if (subject1!=null && !subject1.isEmpty() && !subject1.trim().equalsIgnoreCase("")) {
						subjectNameList.add(subject1);
					}
					
					if (subject2!=null && !subject2.isEmpty() && !subject2.trim().equalsIgnoreCase("")) {
						subjectNameList.add(subject2);
					}
					
					if (subject3!=null && !subject3.isEmpty() && !subject3.trim().equalsIgnoreCase("")) {
						subjectNameList.add(subject3);
					}
					
					if (subject4!=null && !subject4.isEmpty() && !subject4.trim().equalsIgnoreCase("")) {
						subjectNameList.add(subject4);
					}
					
					if (subject5!=null && !subject5.isEmpty() && !subject5.trim().equalsIgnoreCase("")) {
						subjectNameList.add(subject5);
					}
					
					if (subjectNameList.size()>0)
					{
					
						List<Long> subjectIdList = subjectService.getSubjectIdListBySubjectNameList(phaseId,subjectNameList);
					
						Long[] subjectIds = new Long[subjectIdList.size()];
		                for (int i = 0;i < subjectIdList.size();i++){
		                    subjectIds[i] = subjectIdList.get(i);
		                }
		                
		                newUser.setSubjects(subjectIds);
					}
					
															
					saveUser(newUser,UserTypeEnum.TEACHER.getCode());
					
				
										
				}

			} catch (Exception e) {
				e.printStackTrace();
				errorInfo.put("info", "学生保存失败");
				errorList.add(errorInfo);
			}

			iRow++;
		}

		// 统计学校班级、教师、学生数据
		schoolService.updateSchoolTeacherNumBySchoolId(schoolId);

		if (errorList.size() > 0) {
			result.put("statusinfo", "error");
			result.put("errordata", errorList);
		} else {
			result.put("statusinfo", "success");
		}

		return result;
	}
	

}
